/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */ 

package gazzera.swing.network;

/*
 * SimpleTableDemo.java requires no other files.
 */

import gazzera.gui.*;
import gazzera.gui.messages.*;
import gazzera.node.core.*;
import gazzera.swing.*;
import gazzera.swing.model.*;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;

import javax.swing.*;
import javax.swing.table.*;




public class NetworkList extends JTable  {
	
	private List<Connection> list = new ArrayList<Connection>();
	private NodeTableModel model = new NodeTableModel(list);
	private JPopupMenu popupMenu = new JPopupMenu();
	
	private JMenuItem menuConnectNow;
	private JMenuItem menuAdd;
	private JMenuItem menuRemove;
	private JMenuItem menuBan;
	private JMenuItem menuToggleTrust;
	private JMenuItem menuProperties;
	private final Gazzera gazzera;
	
    public NetworkList(final Gazzera gazzera) {
        super();
        this.gazzera = gazzera;
        setModel(model);
       

        setFillsViewportHeight(true);
        setShowGrid(false);
        
        setDragEnabled(false);
        setIntercellSpacing(new Dimension(0,0));
        setCellSelectionEnabled(false);
        setColumnSelectionAllowed(false);
        setRowSelectionAllowed(true);
        setRowHeight(31);
        TableColumn col0 = getColumnModel().getColumn(0); 
        col0.setCellRenderer(new StatusRenderer(false));
        col0.setMaxWidth(28);
        col0.setMinWidth(28);
        col0.setResizable(false);
        col0.setHeaderValue("");
        
        TableColumn col1 = getColumnModel().getColumn(1);
        col1.setCellRenderer(new GidRenderer(false));
        col1.setHeaderValue("Gid");

        TableColumn col2 = getColumnModel().getColumn(2);
        col2.setCellRenderer(new GroupsRenderer(false));
        col2.setMaxWidth(300);
        col2.setPreferredWidth(180);
        col2.setHeaderValue("Groups");

        getTableHeader().setReorderingAllowed(false);
        
        // this.doLayout();
        
        buildMenu();

        
        addMouseListener(new MouseAdapter(){
        	
            public void mouseClicked(MouseEvent e){
             if (e.getClickCount() == 2){
                Connection c = getSelectedConnection();
                if (c.onlineStatus == OnlineStatus.ONLINE)
				{
                	gazzera.createChatWindow(c.hash);
				}
                }
             }
            public void mousePressed(MouseEvent e) {
                showPopup(e);
              }
              public void mouseReleased(MouseEvent e) {
                showPopup(e);
              }
              private void showPopup(MouseEvent e) {
                if (e.isPopupTrigger()) {
                  popupMenu(e.getComponent(), e.getX(), e.getY());
                }
              }

            } );

        
        
    }

	private void buildMenu()
	{
		menuConnectNow = new JMenuItem("Connect now"); 
		menuAdd = new JMenuItem("Add as friend");
		menuRemove = new JMenuItem("Remove from friends");
		menuBan = new JMenuItem("Ban user");
		menuToggleTrust = new JMenuItem("Toggle Trust");
		menuProperties = new JMenuItem("Properties");
		
		menuConnectNow.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				gazzera.gui.pass(new ConnectNode(getSelectedConnection().hash));
			}
		});
		menuAdd.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				Connection c = getSelectedConnection();
				gazzera.gui.pass(new AddFriend(c.nickname + "@"+c.hash));
			}
		});
		menuToggleTrust.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				Connection c = getSelectedConnection();
				gazzera.gui.pass(new ToggleTrust(c.hash));
			}
		});
		menuProperties.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				Connection c = getSelectedConnection();
				PeerPropertiesFolderWindow pro = new PeerPropertiesFolderWindow(gazzera, c);
				pro.setVisible(true);
				
			}
		});
		menuRemove.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				Connection c = getSelectedConnection();
				GuiMessage m = new RemoveFriend(c.nickname + "@"+c.hash);
				System.out.println(gazzera.gui);
				gazzera.gui.pass(m);
			}
		});
		
        popupMenu.add(menuConnectNow);
        popupMenu.add(menuAdd);
        popupMenu.add(menuRemove);
        popupMenu.add(menuToggleTrust);
        popupMenu.add(menuBan);
        popupMenu.add(menuProperties);
	}

	private Connection getSelectedConnection()
	{
		int n = getSelectedRow();
		return (Connection)model.getValueAt(n, 0);
	}
    private void popupMenu(Component comp, int x, int y)
    {
    	if (this.getSelectedRowCount() > 0)
		{
    		
    		Connection c = getSelectedConnection();
    		
    		 menuConnectNow.setEnabled(c.onlineStatus == OnlineStatus.OFFLINE);
    		 menuBan.setEnabled(c.status != FriendStatus.BANNED);
    		 menuAdd.setEnabled((c.status != FriendStatus.FRIEND) && (c.status != FriendStatus.TRUSTED));
    		 menuRemove.setEnabled((c.status == FriendStatus.FRIEND) || (c.status == FriendStatus.TRUSTED));
    		 menuToggleTrust.setEnabled((c.status == FriendStatus.FRIEND) || (c.status == FriendStatus.TRUSTED));
    		 
    		 
    		popupMenu.show(comp, x, y);
		}
    	
    }
    
    public void updateConnection(Connection c)
	{
		
		for (Connection cc : list)
		{
			if (cc.hash.equals(c.hash))
			{
				cc.host = c.host;
				cc.nickname = c.nickname;
				cc.onlineStatus = c.onlineStatus;
				cc.status = c.status;
				cc.port = c.port;
				cc.groups = c.groups;
				model.fireTableRowsUpdated(0, list.size());
				return;
			}
		}
		list.add(c);
		model.fireTableRowsInserted(list.size(), list.size());
		this.repaint();
	}
    
    public Connection getConnection(String hash)
    {
    	for (Connection cc : list)
		{
			if (cc.hash.equals(hash))
			{
				
				return cc;
			}
		}
    	return null;
    }
	
}
